<template>
    <div>
        <van-cell icon="search" v-for="(obj,index) in hightLightSuggestions" :key="index"
            @click="$emit('updata-keywords',suggestion[index])">
            <template #title><span v-html="obj"></span></template>
        </van-cell>
    </div>
</template>

<script>
import { suggestionAPI } from '@/api'
import { debounce } from 'lodash'
export default {
    props: {
        keywords: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            suggestion: []
        }
    },
    watch: {
        //1函数式
        //2对象的写法
        //3字符串的写法(也可以写在handler)在methods身上找办法
        keywords: {
            handler: 'getSearchSuggestions',
            immediate: true
        }
    },
    computed: {
        hightLightSuggestions() {
            const reg = new RegExp(this.keywords, 'gi')
            return this.suggestion.map(item => {
                return item.replace(reg, (match) =>
                    `<span style='color:red'>${match}</span>`)
            })
        }
    },
    methods: {
        getSearchSuggestions: debounce(async function () {
            const { data } = await suggestionAPI(this.keywords)
            this.suggestion = data.data.options.filter(Boolean)
        }, 300)
    }
}

</script>

<style>

</style>